// 首页的逻辑
const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')

const onBox = document.querySelector('.on')
const offBox = document.querySelector('.off')

if (!id) {
  onBox.classList.remove('active')
  offBox.classList.add('active')
}

const xhr = new XMLHttpRequest()

xhr.open('GET', 'http://localhost:8888/users/info?id=' + id)

xhr.onload = function () {
  const res = JSON.parse(xhr.responseText)

  if (res.code === 401) {
    onBox.classList.remove('active')
    offBox.classList.add('active')
  }
  if (res.code === 1) {
    onBox.firstElementChild.innerText = res.info.nickname
    offBox.classList.remove('active')
    onBox.classList.add('active')
  }
}
xhr.setRequestHeader('authorization', token)

xhr.send()

const logoutBtn = document.querySelector('.logout')
logoutBtn.addEventListener('click', async () => {
  const res = await pAjax({
    url: 'http://localhost:8888/users/logout',
    data: { id },
    dataType: 'json'
  })

  if (res.code === 1) {
    window.localStorage.removeItem('id')
    window.localStorage.removeItem('token')
    window.location.reload()
  }
})
